#include "_pch.h"
#include "MObjItem.h"
#include "MTypeNode.h"
#include "MObjCatalog.h"

using namespace wh;
using namespace wh::object_catalog;

//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
MObjItem::MObjItem(const char option)
	:TModelData<rec::Obj>(option)
{
}

//-------------------------------------------------------------------------
bool MObjItem::LoadThisDataFromDb(std::shared_ptr<whTable>& table, const size_t row)
{
	//" SELECT id, pid, obj_label, class_label, class_type, qty, last_log_id "
	T_Data data;

	unsigned int col = 0;

	table->GetAsString(col++, row, data.mID);
	table->GetAsString(col++, row, data.mPID);
	table->GetAsString(col++, row, data.mLabel);
	table->GetAsString(col++, row, data.mQty);
	table->GetAsString(col++, row, data.mLastLogId);

	while (col < table->GetColumnCount())
	{
		wxString str_data;
		table->GetAsString(col, row, str_data);
		data.mProp.emplace_back(str_data);
		col++;
	}


	SetData(data);
	return true;
};


//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
bool MObjArray::GetSelectChildsQuery(wxString& query)const
{
	auto typeItemModel = dynamic_cast<MTypeItem*>(this->GetParent());
	if (typeItemModel)
	{
		auto typeArrayModel = dynamic_cast<MTypeArray*>(typeItemModel->GetParent());
		auto catalogModel = dynamic_cast<MObjCatalog*>(typeArrayModel->GetParent());

		const auto& typeItemData = typeItemModel->GetData();
		const auto& catalogData = catalogModel->GetData();

		wxString qq;
		for (const auto& it : catalogModel->GetFavProps())
		{
			auto typeIt = it.mCls->find(typeItemData.mID);
			if (it.mCls->end() != typeIt)
				qq += wxString::Format(", \"%s\"", it.mLabel);
			else
				qq += wxString::Format(",NULL AS \"%s\"", it.mLabel);
		}


		wxString leftJoin;
		
		if ("1" != typeItemData.mID && "1" == typeItemData.mType)
			leftJoin =wxString::Format(
				" LEFT JOIN t_state_%s USING(obj_id) "
				, typeItemData.mID
				);

		if (catalogModel->mCfg->GetData().mObjCatalog)
		{
			query = wxString::Format(
				"SELECT w_obj.obj_id, obj_pid, w_obj.obj_label, qty, last_log_id %s "
				" FROM w_obj "
				" %s "
				" WHERE obj_pid = %s AND w_obj.cls_id = %s "
				, qq
				, leftJoin
				, catalogData.mObj.mID
				, typeItemData.mID
				);
			return true;
		}
		else
		{
			query = wxString::Format(
				"SELECT w_obj.obj_id, obj_pid, w_obj.obj_label, qty, last_log_id %s "
				" FROM w_obj "
				" %s "
				" WHERE w_obj.cls_id = %s "
				, qq
				, leftJoin
				, typeItemData.mID
				);
			return true;
		}
	}
	return false;
}

